import random

from django.http import JsonResponse

from OAUser.models import *  # 应⽤数据库表
from django.shortcuts import render
from django.shortcuts import redirect
from pymysql import DatabaseError
from OAUser.models import Users, Income, Pay
from django.db import transaction
from . import models
from . import forms
import time
from pyecharts.charts import Bar, Pie
from pyecharts import options as opts


# Create your views here.


def index(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    return render(request, 'login/index.html')


def personal(request):
    uid_nums = request.session['user_uid']
    user_list = Users.objects.get(uid=uid_nums);
    return render(request, 'login/personal-info.html', {
        "user": user_list,
    })


def insertRecord(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    income_form = forms.IncomeForm(request.POST)
    if income_form.is_valid():
        iType = income_form.cleaned_data.get('iType')
        iMoney = income_form.cleaned_data.get('iMoney')
        iRemark = income_form.cleaned_data.get('iRemark')
        iTime = income_form.cleaned_data.get('iTime')
        if iType == "收入":
            models.Income.objects.create(iType=iType,
                                         iMoney=iMoney,
                                         iRemark=iRemark,
                                         iTime=iTime)
        else:
            models.Pay.objects.create(pType=iType,
                                      pMoney=iMoney,
                                      pRemark=iRemark,
                                      pTime=iTime)
    if iType == "收入":
        return redirect('/income')
    else:
        return redirect('/pay')


def income(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    key = request.GET.get("key")
    if key is None:
        new_list = Income.objects.all()
    else:
        new_list = Income.objects.filter(iRemark__contains=key)
    page = request.GET.get("page")
    if page is None:
        page = 1
    else:
        page = int(page)
    page_count = (len(new_list) - 1) // 10 + 1
    page_count = range(1, page_count + 1)
    new_list = new_list[page * 10 - 10: page * 10]
    return render(request, 'login/income.html', locals())


def update_income(request):
    update_id = request.GET.get("iId")
    if request.method == "POST":
        new_type = request.POST.get('iType')
        new_money = request.POST.get('iMoney')
        new_remark = request.POST.get('iRemark')
        new_time = request.POST.get('iTime')
        update_obj = models.Income.objects.get(iId=update_id)
        update_obj.iType = new_type
        update_obj.iMoney = new_money
        update_obj.iRemark = new_remark
        update_obj.iTime = new_time
        update_obj.save()
        return redirect('/income/')
    ret = models.Income.objects.get(iId=update_id)
    return render(request, 'login/update_income.html', {'ret': ret})


def del_income(request):
    income_id = request.GET.get("iId")
    models.Income.objects.filter(iId=income_id).delete()
    return redirect('/income/')


def pay(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    key = request.GET.get("key")
    if key is None:
        new_list1 = Pay.objects.all()
    else:
        new_list1 = Pay.objects.filter(pRemark__contains=key)

    page = request.GET.get("page")
    if page is None:
        page = 1
    else:
        page = int(page)
    page_count = (len(new_list1) - 1) // 10 + 1
    page_count = range(1, page_count + 1)
    new_list1 = new_list1[page * 10 - 10: page * 10]
    return render(request, 'login/pay.html', locals())


def update_pay(request):
    edit_id = request.GET.get("pId")
    if request.method == "POST":
        new_ptype = request.POST.get('pType')
        new_pmoney = request.POST.get('pMoney')
        new_premark = request.POST.get('pRemark')
        new_ptime = request.POST.get('pTime')
        edit_obj = models.Pay.objects.get(pId=edit_id)
        edit_obj.pType = new_ptype
        edit_obj.pMoney = new_pmoney
        edit_obj.pRemark = new_premark
        edit_obj.pTime = new_ptime
        edit_obj.save()
        return redirect('/pay/')
    reet = models.Pay.objects.get(pId=edit_id)
    return render(request, 'login/update_pay.html', {'reet': reet})


def del_pay(request):
    pay_id = request.GET.get("pId")
    models.Pay.objects.filter(pId=pay_id).delete()
    return redirect('/pay/')


def chart(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    # 横坐标，表示日期
    x = []
    # 纵坐标
    y1 = []
    y2 = []
    # 最近十五天的总收入和总支出
    s1 = []
    s2 = []

    i_dir = {}
    p_dir = {}
    # 返回当前时间的时间戳（1970纪元后经过的浮点秒数）
    time_sprite = time.time()
    time_sprite -= 14 * 24 * 60 * 60
    for i in range(15):
        # 得到当前的年月日信息
        local = time.localtime(time_sprite)
        year = local.tm_year
        month = local.tm_mon
        day = local.tm_mday
        date_str = "%d-%02d-%02d" % (year, month, day)
        i_dir[date_str] = 0
        p_dir[date_str] = 0
        # 日期一天天叠加
        x.append(date_str)
        time_sprite += 24 * 60 * 60
    # 获取收入表里面的所有信息
    income_list = Income.objects.all()
    for item in income_list:
        time_str = str(item.iTime)
        # 判断收入日期是否在最近15天内，若在，则计算当天收入金额总和
        if time_str in i_dir:
            i_dir[time_str] += item.iMoney
    # 获取支出表里面的所有信息
    pay_list = Pay.objects.all()
    for item in pay_list:
        time_str = str(item.pTime)
        # 判断支出日期是否在最近15天内，若在，则计算当天支出金额总和
        if time_str in p_dir:
            p_dir[time_str] += item.pMoney

    for day in x:
        y1.append(float(i_dir[day]))
        y2.append(float(p_dir[day]))

    bar = Bar()
    bar.add_xaxis(xaxis_data=x)
    # 第一个参数是图例的名称
    bar.add_yaxis(series_name='收入', y_axis=y1)
    bar.add_yaxis(series_name='支出', y_axis=y2)
    # 添加options
    bar.set_global_opts(title_opts=opts.TitleOpts(title='最近15天的收入与支出'))
    # 生成HTML文件
    bar.render('temp.html')
    html = ""
    with open("temp.html") as f:
        html = f.read()
    html = html.split("</body>")[0]

    # 最近十五天的总收入
    s1 += y1
    # 最近十五天的总支出
    s2 += y2

    names = ['收入', sum(s1)]
    values = ['支出', sum(s2)]
    data = []
    for name,value in names, values:
        datadict = {
            'name': name,
            'value': value
        }
        data.append(datadict)
    return render(request, 'login/chart.html', locals())

@transaction.atomic
def UpdatePro(request):
    """接收参数"""
    uame = request.GET.get('uname')
    upwd = request.GET.get('upwd')
    uemail = request.GET.get('uemail')
    utel = request.GET.get('utel')

    try:
        user = Users.objects.filter(uname__exact=uame).first()
        user.uname = uame
        user.upwd = upwd
        user.uemail = uemail
        user.utel = utel
        user.save()
    except DatabaseError as e:
        print(e)

    return redirect("/personal/")


def login(request):
    if request.session.get('is_login', None):  # 不允许重复登录
        return redirect('/index/')
    if request.method == 'POST':
        login_form = forms.UserForm(request.POST)
        message = '请检查填写的内容！'
        if login_form.is_valid():
            uname = login_form.cleaned_data.get('uname')
            upwd = login_form.cleaned_data.get('upwd')

            try:
                user = models.Users.objects.get(uname=uname)
            except:
                message = '用户不存在！'
                return render(request, 'login/login.html', locals())

            if user.upwd == upwd:
                request.session['is_login'] = True
                request.session['user_uid'] = user.uid
                request.session['user_uname'] = user.uname
                return redirect('/index/')
            else:
                message = '密码不正确！'
                return render(request, 'login/login.html', locals())
        else:
            return render(request, 'login/login.html', locals())

    login_form = forms.UserForm()
    return render(request, 'login/login.html', locals())


def register(request):
    if request.session.get('is_login', None):
        return redirect('/login/')

    if request.method == 'POST':
        register_form = forms.RegisterForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():
            uname = register_form.cleaned_data.get('uname')
            upwd1 = register_form.cleaned_data.get('upwd1')
            upwd2 = register_form.cleaned_data.get('upwd2')
            uemail = register_form.cleaned_data.get('uemail')
            utel = register_form.cleaned_data.get('utel')
            usex = register_form.cleaned_data.get('usex')

            if upwd1 != upwd2:
                message = '两次输入的密码不同！'
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = models.Users.objects.filter(uname=uname)
                if same_name_user:
                    message = '用户名已经存在'
                    return render(request, 'login/register.html', locals())
                same_email_user = models.Users.objects.filter(uemail=uemail)
                if same_email_user:
                    message = '该邮箱已经被注册了！'
                    return render(request, 'login/register.html', locals())
                print(uname, upwd1, uemail, utel, usex)
                models.Users.objects.create(uname=uname,
                                            upwd=upwd1,
                                            uemail=uemail,
                                            utel=utel,
                                            usex=usex)
                return redirect('/login/')
        else:
            return render(request, 'login/register.html', locals())
    register_form = forms.RegisterForm()
    return render(request, 'login/register.html', locals())


def logout(request):
    if not request.session.get('is_login', None):
        # 如果本来就未登录，也就没有登出一说
        return redirect("/login/")
    request.session.flush()
    # 或者使用下面的方法
    # del request.session['is_login']
    # del request.session['user_id']
    # del request.session['user_name']
    return redirect("/login/")

